import { useEffect, useMemo, useState } from "react";
import { Checkbox, Form, Space, Tag, Popup, Divider, Input, TextArea, Picker,Radio, Cascader,Toast } from "antd-mobile";
import { DownOutline } from 'antd-mobile-icons';
import dayjs from "dayjs";
import { useNavigate, useSearchParams } from "react-router-dom";
import Styles from "./index.module.less";
import store from '@/reducer/store'
import country from '@/assets/ts/country'
import DatePopup from '@/components/DatePopup'
import { update } from "@/reducer/ProjectInfo/action";
import { getPurposeInfo,editDetailInfo } from '@/service/projectDetail'
import departmentData from '@/assets/ts/department'
import industryData from '@/assets/ts/industry'
import rankData from '@/assets/ts/rank'
import investmentTypeData from '@/assets/ts/investmentType'

const Index: React.FC<any> = () => {
    const yearArr = [dayjs().get("year") - 3,dayjs().get("year") - 2,dayjs().get("year") -1]
    const [search] = useSearchParams();
    const searchId = search?.get('id')
    const navigate = useNavigate();
    const [ params, setParams ] = useState({
        contacts:'',
        contactsPhone:'',
        companyName:'',
        businessAddress:'',
        primaryBusiness:'',
        businessStatus:[],
        operationStateTax1:'',
        operationStateTax2:'',
        operationStateTax3:'',
        operationStateRevenue1:'',
        operationStateRevenue2:'',
        operationStateRevenue3:'',
        companyProfile:'',
        isMoved:'',
        investorName:'',
        projectName:'',
        inputProjectName:'',
        planSettledAddress:'',
        operationForecastTax1:'',
        operationForecastTax2:'',
        operationForecastTax3:'',
        operationForecastRevenue1:'',
        operationForecastRevenue2:'',
        operationForecastRevenue3:'',
        planInvestVolume:'',
        hopeJointDept:[],
        havePolicySupport:'',
        settledAppeal:'',
        isOutside: null
    });
    const changeParams = (val:any,key:string)=>{
        setParams((value:any)=>{
            value[key] = val
            return {...value}
        })
    }
    const industryColumns = [industryData.map((item:any)=>{
        return {
            label:item.value,
            value:item.value,
        }
    })]
    const [ industryVis,setIndustryVis ] = useState(false);
    const [ industryValue,setIndustryValue ] = useState<any>([]);
    const [ countryValue,setCountryValue] = useState([]);
    const [ countryKeys,setCountryKeys] = useState([]);
    const [ countryVis,setCountryVis] = useState(false);
    const findCountry = (v:any, list:any):any => {
        let data;
        (list || []).map((i:any) => {
          if (i.value === v) {
            data = [i];
          } else {
            const child = findCountry(v, i.children);
            if (child) {
              data = child;
            }
          }
        });
        return data;
      };
    const enterCountry = (value:any,e:any)=>{
        let countryArr:any = []
        value.map((item:any)=>{
            countryArr.push(findCountry(item,country)[0]); 
        })
        let countryArrLabels = countryArr.map((item:any)=>{
            return item.label
        })
        setCountryKeys(countryArrLabels)
        setInpustProjectName({text1:countryArrLabels})
        setCountryValue(value);
        setCountryVis(false)
    }
    const investmentTypeColumns = [investmentTypeData]
    const [ investmentTypeVis,setInvestmentTypeVis ] = useState(false);
    const [ investmentTypeValue,setInvestmentTypeValue ] = useState<any>([]);
    const [ DatePopupVis,setDatePopupVis ] = useState(false)
    const [ DatePopupTime,setDatePopupTime ] = useState('')
    const showPopup=(status:any)=>{
        setDatePopupVis(status)
    }
    const enterDate=(e:any)=>{
        let date:any = dayjs(e).startOf('month').format('YYYY-MM')
        setDatePopupTime(date)
    }
    const getPurposeData = async() => {
        const res:any = await getPurposeInfo({id: searchId})
        const { code, data } = res?.data
        if(code == 0) {
            let {
                contacts,
                contactsPhone,
                projectName,
                companyName,
                businessAddress,
                primaryBusiness,
                businessStatus,
                planInvestVolume,
                businessClass,
                operationStateTax1,
                operationStateTax2,
                operationStateTax3,
                operationStateRevenue1,
                operationStateRevenue2,
                operationStateRevenue3,
                companyProfile,
                isMoved,
                investType,
                planSettledAddress,
                planSettledTime,
                operationForecastTax1,
                operationForecastTax2,
                operationForecastTax3,
                operationForecastRevenue1,
                operationForecastRevenue2,
                operationForecastRevenue3,
                hopeJointDept,
                havePolicySupport,
                settledAppeal,
                isOutside
            } = data;
            setParams((value:any)=>{
                value.contacts = contacts
                value.contactsPhone = contactsPhone
                value.projectName = projectName
                value.companyName = companyName
                value.businessAddress = businessAddress
                value.primaryBusiness = primaryBusiness
                value.businessStatus = businessStatus?businessStatus.split(','):[]
                value.operationStateTax1 = operationStateTax1 || ''
                value.operationStateTax2 = operationStateTax2 || ''
                value.operationStateTax3 = operationStateTax3 || ''
                value.operationStateRevenue1 = operationStateRevenue1 || ''
                value.operationStateRevenue2 = operationStateRevenue2 || ''
                value.operationStateRevenue3 = operationStateRevenue3 || ''
                value.companyProfile = companyProfile
                value.isMoved = isMoved
                value.isOutside = isOutside
                value.investorName = companyName
                value.inputProjectName = projectName
                value.planSettledAddress = planSettledAddress
                value.operationForecastTax1 = operationForecastTax1 || ''
                value.operationForecastTax2 = operationForecastTax2 || ''
                value.operationForecastTax3 = operationForecastTax3 || ''
                value.operationForecastRevenue1 = operationForecastRevenue1 || ''
                value.operationForecastRevenue2 = operationForecastRevenue2 || ''
                value.operationForecastRevenue3 = operationForecastRevenue3 || ''
                value.planInvestVolume = planInvestVolume
                value.hopeJointDept = hopeJointDept?hopeJointDept.split(','):[]
                value.havePolicySupport = havePolicySupport
                value.settledAppeal = settledAppeal
                
                return {...value}
            })
            businessClass && setIndustryValue([businessClass])
            investType && setInvestmentTypeValue([investType])
            planSettledTime && setDatePopupTime(planSettledTime)
        }
    }
    const changeBusinessStatus = (e:any)=>{
        setParams((value:any)=>{
            value.businessStatus = e
            return {...value}
        })
    }
    const setInpustProjectName = ({text1 = countryKeys,text2 = params.investorName,text3 = investmentTypeValue}:any={})=>{
        text1 = text1.join('/')
        text3 = text3.toString()
        let textArr:any = []
        text1 && textArr.push(text1)
        text2 && textArr.push(text2)
        text3 && textArr.push(text3)
        setParams((value:any)=>{
            value.inputProjectName = textArr.join('-')
            return {...value}
        })
    }
    const cancel = ()=>{
        navigate(-1)
    }
    const submit = async()=>{
        const verify = [
            [params.contacts==='','联系人不能为空'],
            [params.contactsPhone==='','联系电话不能为空'],
            [params.companyName==='','企业（项目投资方）不能为空'],
            [params.businessAddress==='','现经营地址不能为空'],
            [params.primaryBusiness==='','主经营业务不能为空'],
            [industryValue==='','行业门类不能为空'],
            [params.businessStatus.length===0,'请选择行业地位'],
            [params.operationStateTax1==='' && params.operationStateTax2==='' && params.operationStateTax3==='','请输入税收贡献(万元)'],
            [params.operationStateRevenue1==='' && params.operationStateRevenue2==='' && params.operationStateRevenue3==='','请输入营收或产值(万元)'],
            [params.companyProfile==='','企业基本情况介绍不能为空'],
            [params.isMoved==='','请选择是否本企业（投资方）迁入福田'],
            [params.isOutside== null && params.isMoved == '1','请选择迁入方式'],
            [params.inputProjectName==='','项目名称不能为空'],
            [params.planSettledAddress==='','拟落户选址不能为空'],
            [DatePopupTime==='','请选择拟落户时间'],
            [params.operationForecastTax1==='' && params.operationForecastTax2==='' && params.operationForecastTax3==='',`请输入预测企业落户的税收贡献(万元)`],
            [params.operationForecastRevenue1==='' && params.operationForecastRevenue2==='' && params.operationForecastRevenue3==='',`请输入预测企业落户的营收或产值(万元)`],
            [params.planInvestVolume==='','计划未来5年投资额（万元）不能为空'],
            [params.hopeJointDept.length===0,'请选择希望哪个部门与您对接'],
            [params.havePolicySupport==='','已享受政府政策支持情况不能为空'],
        ]
        for(let i = 0;i<verify.length;i++){
            if(verify[i][0]){
                return Toast.show({content:verify[i][1]})
            }
        }
        let queryData = {
            id:searchId,
            businessClass:industryValue.toString(),
            planSettledTime:DatePopupTime
        }
        for(let key in params){
            if(['businessStatus','hopeJointDept'].includes(key)){
                params[key] = params[key].toString()
            }
            if(key=='projectName' && params.inputProjectName){
                params.projectName = params.inputProjectName
            }
            if(!['investorName','inputProjectName'].includes(key)){
                queryData[key] = params[key]
            }
        }
        const res:any = await editDetailInfo(queryData)
        const { code, msg } = res?.data
        if(code == 0) {
            navigate(-1)
        }
        Toast.show({content:msg})
    }
    useEffect(()=>{
        getPurposeData()
    },[])
    return(<>
    <div className={Styles.Baseinfo}>
        <div className={Styles.blockItem}>
            <div className={Styles.BaseinfoTitle}>联系方式</div>
            <div className={Styles.BaseinfoBlock}>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>联系人：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Input
                            placeholder='请输入'
                            value={params.contacts}
                            onChange={val => {
                                changeParams(val,'contacts')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>联系电话：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Input
                            placeholder='请输入'
                            value={params.contactsPhone}
                            onChange={val => {
                                changeParams(val,'contactsPhone')
                            }}
                        />
                    </div>
                </div>
            </div>
        </div>
        <div className={Styles.blockItem}>
            <div className={Styles.BaseinfoTitle}>企业（投资方）情况介绍</div>
            <div className={Styles.BaseinfoBlock}>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>企业（项目投资方）：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Input
                            placeholder='请输入'
                            value={params.companyName}
                            onChange={val => {
                                changeParams(val,'companyName')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>现经营地址：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Input
                            placeholder='请输入'
                            value={params.businessAddress}
                            onChange={val => {
                                changeParams(val,'businessAddress')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>主经营业务：</div>
                    <div className={Styles.BaseinfoInput}>
                        <TextArea
                            placeholder='请输入'
                            value={params.primaryBusiness}
                            onChange={val => {
                                changeParams(val,'primaryBusiness')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>行业门类：</div>
                    <div className={Styles.BaseinfoInput} onClick={()=>{setIndustryVis(true)}}>
                        <div className={Styles.BaseinfoText}>{industryValue}</div>
                        <DownOutline />
                        <Picker
                        columns={industryColumns}
                        visible={industryVis}
                        onClose={() => {
                            setIndustryVis(false)
                        }}
                        value={industryValue}
                        onConfirm={(v:any) => {
                            setIndustryValue(v)
                        }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>行业地位：</div>
                    <div className={Styles.BaseinfoInput}>
                        <div>
                            <Checkbox.Group value={params.businessStatus} onChange={(e)=>changeBusinessStatus(e)}>
                                {rankData.map((item:any,index:any)=>{
                                    return <div className={Styles.CheckboxItem} key={index}>
                                        <Checkbox value={item.id}></Checkbox>{item.name}
                                    </div>
                                })}
                            </Checkbox.Group>
                        </div>
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>经营情况：</div>
                    <div className={Styles.BaseinfoInput}>
                        <table className={Styles.table}>
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>税收贡献(万元)</th>
                                    <th>营收或产值(万元)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>{yearArr[0]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateTax1}
                                        onChange={val => {
                                            changeParams(val,'operationStateTax1')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateRevenue1}
                                        onChange={val => {
                                            changeParams(val,'operationStateRevenue1')
                                        }}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>{yearArr[1]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateTax2}
                                        onChange={val => {
                                            changeParams(val,'operationStateTax2')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateRevenue2}
                                        onChange={val => {
                                            changeParams(val,'operationStateRevenue2')
                                        }}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>{yearArr[2]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateTax3}
                                        onChange={val => {
                                            changeParams(val,'operationStateTax3')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationStateRevenue3}
                                        onChange={val => {
                                            changeParams(val,'operationStateRevenue3')
                                        }}/>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>企业基本情况介绍：</div>
                    <div className={Styles.BaseinfoInput}>
                        <TextArea
                            placeholder='请输入'
                            value={params.companyProfile}
                            onChange={val => {
                                changeParams(val,'companyProfile')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>是否本企业（投资方）迁入福田：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Radio.Group value={params.isMoved} onChange={(e:any)=>{
                            setParams((value:any)=>{
                                value.isMoved = e
                                return {...value}
                            })
                        }}>
                            <div className={Styles.CheckboxItem}>
                                <Radio value={1}></Radio>是
                            </div>
                            <div className={Styles.CheckboxItem}>
                                <Radio value={0}></Radio>否
                            </div>
                        </Radio.Group>
                    </div>
                </div>
                {params.isMoved == '1' && <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>迁入方式：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Radio.Group value={params.isOutside} onChange={(e:any)=>{
                            setParams((value:any)=>{
                                value.isOutside = e
                                return {...value}
                            })
                        }}>
                            <div className={Styles.CheckboxItem}>
                                <Radio value={0}></Radio>市内迁入
                            </div>
                            <div className={Styles.CheckboxItem}>
                                <Radio value={1}></Radio>市外迁入
                            </div>
                        </Radio.Group>
                    </div>
                </div>}
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>项目名称：</div>
                    <div className={Styles.BaseinfoInput} onClick={()=>{setCountryVis(true)}}>
                        <div className={Styles.projectNameItem}>国别/地区名</div>
                        <div className={Styles.BaseinfoText}>{countryKeys.join('/') || '请选择'}</div>
                        <DownOutline />
                        <Cascader 
                        options={country} 
                        value={countryValue} 
                        visible={countryVis} 
                        onCancel={()=>{setCountryVis(false)}} 
                        onConfirm={(value,e)=>{enterCountry(value,e)}}/>
                    </div>
                    <div className={Styles.BaseinfoInput}>
                        <div className={Styles.projectNameItem}>投资方名称</div>
                        <Input
                            placeholder='请输入'
                            disabled
                            value={params.investorName}
                            onChange={val => {
                                changeParams(val,'investorName')
                            }}
                        />
                    </div>
                    <div className={Styles.BaseinfoInput} onClick={()=>{setInvestmentTypeVis(true)}}>
                        <div className={Styles.projectNameItem}>投资类型</div>
                        <div className={Styles.BaseinfoText}>{investmentTypeValue}</div>
                        <DownOutline />
                        <Picker
                        columns={investmentTypeColumns}
                        visible={investmentTypeVis}
                        onClose={() => {
                            setInvestmentTypeVis(false)
                        }}
                        value={investmentTypeValue}
                        onConfirm={(v:any) => {
                            setInvestmentTypeValue(v)
                            setInpustProjectName({text3:v})
                        }}
                        />
                    </div>
                    <div className={Styles.BaseinfoInput}>
                        <div className={Styles.projectNameItem}>自定义输入</div>
                        <Input
                            placeholder='请输入'
                            value={params.inputProjectName}
                            onChange={val => {
                                changeParams(val,'inputProjectName')
                            }}
                        />
                    </div>
                </div>
            </div>
        </div>
        <div className={Styles.blockItem}>
            <div className={Styles.BaseinfoTitle}>预测落户后情况介绍</div>
            <div className={Styles.BaseinfoBlock}>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>拟落户选址：</div>
                    <div className={Styles.BaseinfoInput}>
                        <TextArea
                            placeholder='请输入'
                            value={params.planSettledAddress}
                            onChange={val => {
                                changeParams(val,'planSettledAddress')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>拟落户时间：</div>
                    <div className={Styles.BaseinfoInput} onClick={()=>showPopup(true)}>
                        <div className={Styles.BaseinfoText}>{DatePopupTime || '请选择'}</div>
                        <DatePopup vis={DatePopupVis} showPopup={showPopup} enterDate={enterDate}/>
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>经营预测：</div>
                    <div className={Styles.BaseinfoInput}>
                        <table className={Styles.table}>
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>预测企业落户的税收贡献(万元)</th>
                                    <th>预测企业落户的营收或产值(万元)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>{yearArr[0]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastTax1}
                                        onChange={val => {
                                            changeParams(val,'operationForecastTax1')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastRevenue1}
                                        onChange={val => {
                                            changeParams(val,'operationForecastRevenue1')
                                        }}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>{yearArr[1]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastTax2}
                                        onChange={val => {
                                            changeParams(val,'operationForecastTax2')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastRevenue2}
                                        onChange={val => {
                                            changeParams(val,'operationForecastRevenue2')
                                        }}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>{yearArr[2]}年</td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastTax3}
                                        onChange={val => {
                                            changeParams(val,'operationForecastTax3')
                                        }}/>
                                    </td>
                                    <td>
                                        <Input
                                        placeholder='请输入'
                                        value={params.operationForecastRevenue3}
                                        onChange={val => {
                                            changeParams(val,'operationForecastRevenue3')
                                        }}/>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>计划未来5年投资额（万元）：</div>
                    <div className={Styles.BaseinfoInput}>
                        <Input
                            placeholder='请输入'
                            value={params.planInvestVolume}
                            onChange={val => {
                                changeParams(val,'planInvestVolume')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>希望哪个部门与您对接：</div>
                    <div className={Styles.BaseinfoInput}>
                        <div>
                            <Checkbox.Group value={params.hopeJointDept} onChange={val => {changeParams(val,'hopeJointDept')}}>
                                {departmentData.map((item:any,index:any)=>{
                                    return <div className={Styles.CheckboxItem} key={index}>
                                    <Checkbox value={item.value}></Checkbox>{item.label}
                                </div>
                                })}
                            </Checkbox.Group>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div className={Styles.blockItem}>
            <div className={Styles.BaseinfoTitle}>其他</div>
            <div className={Styles.BaseinfoBlock}>
                <div className={Styles.BaseinfoItem}>
                    <div className={Styles.BaseinfoKey}>已享受政府政策支持情况：</div>
                    <div className={Styles.BaseinfoInput}>
                        <TextArea
                            placeholder='请输入'
                            value={params.havePolicySupport}
                            onChange={val => {
                                changeParams(val,'havePolicySupport')
                            }}
                        />
                    </div>
                </div>
                <div className={Styles.BaseinfoItem}>
                    <div className={`${Styles.BaseinfoKey} ${Styles.noRequire}`}>落户诉求：</div>
                    <div className={Styles.BaseinfoInput}>
                        <TextArea
                            placeholder='请输入'
                            value={params.settledAppeal}
                            onChange={val => {
                                changeParams(val,'settledAppeal')
                            }}
                        />
                    </div>
                </div>
            </div>
        </div>
        <div className={Styles.submitBtn}>
            <div className={Styles.btnCancel} onClick={()=>cancel()}>取消</div>
            <div className={Styles.btnEnter} onClick={()=>submit()}>确认</div>
        </div>
    </div>
    </>)
}
export default Index;